package com.example.service;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.cache.configuration.Factory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class TenantAwareDataSourceFactory implements Factory<DataSource> {

    private static final Map<String,DataSource> dataSources=new HashMap<>();

    private Tenant tenant;

    public TenantAwareDataSourceFactory(Tenant tenant){
        this.tenant = tenant;
    }

    public void setTenant(Tenant tenant) {
        this.tenant = tenant;
    }

    //TODO: 获取配置中的连接参数
    @Override
    public DataSource create() {
        DataSource dataSource = dataSources.get(tenant.getSchema());
        if (dataSource==null){
            HikariConfig config = new HikariConfig();
            config.setDriverClassName("com.mysql.cj.jdbc.Driver");
            config.setJdbcUrl("jdbc:mysql://192.168.0.100:3306/" + tenant.getSchema());
            config.setUsername("user.name");
            config.setPassword("user.password");
            config.setMaximumPoolSize(10);
            config.setMinimumIdle(2);
            dataSource = new HikariDataSource(config);
            dataSources.put(tenant.getSchema(),dataSource);
        }
        return dataSource;
    }
}
